package com.aust.demo01;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * 练习Thread：实现多线程同步下载图片
 */
public class TestThread2 extends Thread {

    private String url; //网络图片地址
    private String name; //保存文件名

    public TestThread2(String url, String name) {
        this.url = url;
        this.name = name;
    }

    /**
     * 下载图片线程的执行体
     */
    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("下载文件名为：" + name);
    }

    public static void main(String[] args) {

        // 线程1
        String url1 = "https://picx.zhimg.com/v2-6ca9e1a5c977ad26a53fcc11a7ba9f57_720w.jpg?source=172ae18b";
        TestThread2 t1 = new TestThread2(url1, "1.jpg");

        // 线程2
        String url2 = "https://picx.zhimg.com/v2-6ca9e1a5c977ad26a53fcc11a7ba9f57_720w.jpg?source=172ae18b";
        TestThread2 t2 = new TestThread2(url2, "2.jpg");

        // 线程3
        String url3 = "https://picx.zhimg.com/v2-6ca9e1a5c977ad26a53fcc11a7ba9f57_720w.jpg?source=172ae18b";
        TestThread2 t3 = new TestThread2(url3, "3.jpg");

        t1.start();
        t2.start();
        t3.start();

    }

}

/**
 * 下载器
 */
class WebDownloader {
    /**
     * 下载方法
     */
    public void downloader(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader方法出现问题！");
        }
    }
}